/**
 * author:Administrator
 * date:2016/1/4
 * desc:TODO
 *
 ** mongodb 事务  two phase commits
 ** refer : https://docs.mongodb.org/manual/tutorial/perform-two-phase-commits/
 *
 * 正常流程 7步
 * edit步骤中，必须记录响应的transid
 *
 *      docA    docB    trans
 *      -       -       init
 *      -       -       pending
 *      edit    -       -
 *      -       edit    -
 *      -       -       applied
 *      edit    -       -
 *      -       edit    -
 *      -       -       done
 *
 * -------recover from pending-------
 * pre  -       -       pending
 *      -       -       cancelling
 *      edit    -       -
 *      -       edit    -
 *      -       -       canceled
 */

'use strict';

var Model = require('../model/transCoupon.js');
var counter = require('./counter.js');
var myCounter = counter.bindCounter(counter.TypesEnum.transactionid);
var dao = {};
module.exports = dao;

dao.empty = function* () {
  return yield Model.remove({});
};

dao.remove = function*(tid) {
  return yield Model.remove({tid: tid});
};

dao.add = function* (cvid, cuid, qty) {
  var tid = yield myCounter();
  var entity = new Model({
    tid: tid,
    cvid: cvid,
    cuid: cuid,
    qty: qty,
    state: 'initial'
  });
  return yield entity.save();
};

/**
 * cb(err,doc)
 */
dao.updateState = function* (id, state, cb) {
  return yield Model.findOneAndUpdate(
    {id: id},
    {$set: {state: state}},
    {upsert: true, 'new': true});
};

dao.findOne = function *(query) {
  return yield Model.findOne(query);
};

dao.find = function *(query) {
  return yield Model.find(query);
};

